package dtaskboard.server.dao;

import java.util.List;

import javax.persistence.Query;

import dtaskboard.entities.User;

public class UserDao extends GenericDao<User> {

  private static final String userQuery = "FROM " + User.class.getSimpleName()
      + " WHERE login = :login";

  @Override
  public Class<User> getEntityClass() {
    return User.class;
  }

  public boolean authenticate(String login, String password) {
    if (login == null || password == null) {
      return false;
    }
    User user = this.find(login);
    if (user == null) {
      return false;
    }
    if (password.equals(user.getPassword())) {
      return true;
    }

    return false;
  }

  public User find(String login) {
    Query query = EMFactory.get().createQuery(UserDao.userQuery);
    query.setParameter("login", login);

    @SuppressWarnings("unchecked")
    List<User> results = query.getResultList();
    if (results == null || results.size() != 1) {
      return null;
    }
    return results.get(0);
  }
}
